var input = document.querySelector('#search');
var hot = document.querySelector('#hot');
var mm1 = document.querySelector('.mm1');
var mm2 = document.querySelector('.mm2');
// var rep = document.querySelector('.rep');
input.onfocus = function() {
    var timer;
    this.onkeyup = function() {
        var val = this.value;
        clearTimeout(timer);
        timer = setTimeout(function() {
            if (val != '') {
                show(val);
                var hist = document.querySelectorAll('.hist');
                var fg = true;
                console.log(hist);
                hist.forEach(item => {
                    if (item.innerHTML == val) {
                        fg = false;
                    }
                })
                if (fg) {
                    hot.innerHTML += `<li><a href="#" class='hist' onclick=show("${val}")>${val}</a></li>`
                }
            }
        }, 1200)
    }
}

function show(val) {
    mm2.style.display = 'block';
    ajax({
        url: '/search',
        method: 'get',
        data: { keywords: val, },
        success: function(resp) {
            localStorage.clear();
            var data = resp.result.songs;
            var rep = document.querySelector('.rep');
            var result = "";
            localStorage.setItem('n', 0);
            for (var i = 0; i < data.length; i++) {
                localStorage.setItem(`musicId${i}`, data[i].id)
                result += `<li>
                    <div class="prep">
                        <div class="musicPro">
                            <div class="musicName">${data[i].name}</div>
                            <div class="musicAuthor">${data[i].artists[0].name}</div>
                        </div>
                        <a href="#">
                            <div onclick=jump("${data[i].id}") class="musicPlay mp">
                                <span class="glyphicon glyphicon-play-circle" aria-hidden="true"></span>
                            </div>
                        </a>
                    </div>
                </li>`;
            }
            rep.innerHTML = result;
        }
    })
}

function jump(id) {
    window.location.href = `play.html?id=${id}`;
}


input.onblur = function() {
    if (this.value == '') {
        mm2.style.display = 'none';
    }
}

ajax({
    url: '/search/hot',
    method: 'get',
    success: function(resp) {
        hot.innerHTML = '';
        var data = resp.result.hots
        var result = '';
        for (let i = 0; i < data.length; i++) {
            result += `
            <li><a href="#" class='hist' onclick=show("${data[i].first}")>${data[i].first}</a></li>
            `
        }
        hot.innerHTML = result;
    }
})